import crypto from '../utils/crypto';


export default class Tokenmgr{

    static tokens: {[key:string]: token} = {};
    static users = {};
    

    static createToken(userId, lifeTime){

        let token = this.users[userId];
        if(token != null){
            this.delToken(token);
        }

        const time = Date.now();
        token = crypto.md5(userId + '!@#$%^&' + time);
        this.tokens[token] = {
            userId: userId,
            time: time,
            lifeTime: lifeTime,
        };
        this.users[userId] = token;
        return token;

    }

    static delToken(token){
        const info = this.tokens[token];
        if(info != null){
            this.tokens[token] = null;
            this.users[info.userId] = null;
        }
    }

    static isTokenValid(token){
        const info = this.tokens[token];
        if(info == null){
            return false;
        }
        if(info.time + info.lifeTime < Date.now()){
            return false;
        }
        return true;
    }

    static getUserID(token){
        return this.tokens[token].userId;
    }
}